package cn.practice.chat.qiniu.utils;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName QiniuUtils
 * @Description:
 * @Author A-TAO
 * @Date 2022/11/18
 * @Version V1.0
 **/
@Slf4j
@Component
public class QiniuUtils {

    // 设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "MxJnl6i7GJNj1Szo_GiaAM_N-6hJ10odYVY4FtkZ";
    String SECRET_KEY = "fp5I4AhLx68AbU04aS0eEqgx6yZVSbEsrdRWLpqp";
    // 要上传的空间（创建空间的名称）
    String bucket = "zhutao2";
    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.regionCnEast2());
    UploadManager uploadManager = new UploadManager(cfg);

    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);


    // 使用的是测试域名
    private static String QINIU_IMAGE_DOMAIN = "http://rli175bwk.bkt.clouddn.com/";

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    private String getUpToken() {
        return auth.uploadToken(bucket);
    }

    private String filePath(){
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        return sdf.format(date);
    }


    public String uploadFile(MultipartFile file) throws IOException {
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();

            String fileName =filePath() +"/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            log.info(res.address);
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                log.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            log.error("七牛异常:" + e.getMessage());
            return null;
        }

    }

}
